package cn.iocoder.yudao.module.bpm.service.sourcecatalog;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.bpm.api.task.BpmProcessInstanceApi;
import cn.iocoder.yudao.module.bpm.api.task.dto.BpmProcessInstanceCreateReqDTO;
import cn.iocoder.yudao.module.bpm.controller.admin.journal.vo.JournalSaveReqVO;
import cn.iocoder.yudao.module.bpm.controller.admin.source.vo.SourceSaveReqVO;
import cn.iocoder.yudao.module.bpm.controller.admin.sourcecatalog.vo.SourceCatalogPageReqVO;
import cn.iocoder.yudao.module.bpm.controller.admin.sourcecatalog.vo.SourceCatalogSaveReqVO;
import cn.iocoder.yudao.module.bpm.dal.dataobject.sourceapply.SourceApplyDO;
import cn.iocoder.yudao.module.bpm.dal.dataobject.sourcecatalog.SourceCatalogDO;
import cn.iocoder.yudao.module.bpm.dal.mysql.sourcecatalog.SourceCatalogMapper;
import cn.iocoder.yudao.module.bpm.enums.task.BpmProcessInstanceStatusEnum;
import cn.iocoder.yudao.module.bpm.service.source.SourceService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.bpm.enums.ErrorCodeConstants.*;

/**
 * 资源编目 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class SourceCatalogServiceImpl implements SourceCatalogService {

    public static final String PROCESS_KEY = "sourcecatalog";

    @Resource
    private SourceCatalogMapper sourceCatalogMapper;

    @Resource
    private BpmProcessInstanceApi processInstanceApi;

    @Resource
    private SourceService sourceService;

    @Override
    public Long createSourceCatalog(Long userId,SourceCatalogSaveReqVO createReqVO) {
        // 插入
        SourceCatalogDO sourceCatalog = BeanUtils.toBean(createReqVO, SourceCatalogDO.class);
        sourceCatalog.setBizDelected(0);
        sourceCatalogMapper.insert(sourceCatalog);
        if(createReqVO.getOperateFlag().equals("submit")){
            String processInstanceId = processInstanceApi.createProcessInstance(userId,
                    new BpmProcessInstanceCreateReqDTO().setProcessDefinitionKey(PROCESS_KEY)
                            //.setVariables(processInstanceVariables)
                            .setBusinessKey(String.valueOf(sourceCatalog.getId()))
                            .setStartUserSelectAssignees(createReqVO.getStartUserSelectAssignees())).getCheckedData();
            // 将工作流的编号，更新到 OA 请假单中
            sourceCatalogMapper.updateById(new SourceCatalogDO().setId(sourceCatalog.getId())
                    .setProcessInstanceId(processInstanceId)
                    .setStatus(BpmProcessInstanceStatusEnum.RUNNING.getStatus()));
        } else {
            sourceCatalogMapper.updateById(new SourceCatalogDO().setId(sourceCatalog.getId())
                    .setStatus(BpmProcessInstanceStatusEnum.NOT_START.getStatus()));
        }
        // 返回
        return sourceCatalog.getId();
    }

    @Override
    public void updateSourceCatalog(Long userId,SourceCatalogSaveReqVO updateReqVO) {
        // 校验存在
        validateSourceCatalogExists(updateReqVO.getId());
        // 更新
        SourceCatalogDO updateObj = BeanUtils.toBean(updateReqVO, SourceCatalogDO.class);
        sourceCatalogMapper.updateById(updateObj);

        if(updateReqVO.getOperateFlag().equals("submit")){
            String processInstanceId = processInstanceApi.createProcessInstance(userId,
                    new BpmProcessInstanceCreateReqDTO().setProcessDefinitionKey(PROCESS_KEY)
                            //.setVariables(processInstanceVariables)
                            .setBusinessKey(String.valueOf(updateObj.getId()))
                            .setStartUserSelectAssignees(updateReqVO.getStartUserSelectAssignees())).getCheckedData();
            // 将工作流的编号，更新到 OA 请假单中
            sourceCatalogMapper.updateById(new SourceCatalogDO().setId(updateObj.getId())
                    .setProcessInstanceId(processInstanceId)
                    .setStatus(BpmProcessInstanceStatusEnum.RUNNING.getStatus()));
        } else {
            sourceCatalogMapper.updateById(new SourceCatalogDO().setId(updateObj.getId())
                    .setStatus(BpmProcessInstanceStatusEnum.NOT_START.getStatus()));
        }
    }

    @Override
    public void deleteSourceCatalog(Long id) {
        // 校验存在
        validateSourceCatalogExists(id);
        // 删除
        sourceCatalogMapper.updateById(new SourceCatalogDO().setId(id).setBizDelected(1));
    }

    private void validateSourceCatalogExists(Long id) {
        if (sourceCatalogMapper.selectById(id) == null) {
            throw exception(SOURCE_CATALOG_NOT_EXISTS);
        }
    }

    @Override
    public SourceCatalogDO getSourceCatalog(Long id) {
        return sourceCatalogMapper.selectById(id);
    }

    @Override
    public PageResult<SourceCatalogDO> getSourceCatalogPage(SourceCatalogPageReqVO pageReqVO) {
        return sourceCatalogMapper.selectPage(pageReqVO);
    }

    @Override
    public void updateLeaveStatus(Long id, Integer status) {
        validateLeaveExists(id);
        sourceCatalogMapper.updateById(new SourceCatalogDO().setId(id).setStatus(status));
        if(status.equals(BpmProcessInstanceStatusEnum.APPROVE.getStatus())){
            sourceService.updateSource(new SourceSaveReqVO().setId(sourceCatalogMapper.selectById(id).getSourceId()).setSourceStatus("1"));
        }
    }

    @Override
    public void rebackSourceCatalog(SourceCatalogSaveReqVO updateReqVO) {
        validateLeaveExists(updateReqVO.getId());
        sourceCatalogMapper.updateById(new SourceCatalogDO().setId(updateReqVO.getId()).setBizDelected(0));
    }

    private void validateLeaveExists(Long id) {
        if (sourceCatalogMapper.selectById(id) == null) {
            throw exception(OA_LEAVE_NOT_EXISTS);
        }
    }

}